import 'package:flutter_test/flutter_test.dart';
import 'package:logger/logger.dart';
import '../lib/services/statistics_service.dart';
import '../lib/core/database_helper.dart';

void main() {
  group('StatisticsService Tests', () {
    late StatisticsService statisticsService;
    late DatabaseHelper databaseHelper;

    setUpAll(() async {
      // 初始化数据库
      await DatabaseHelper.initializeDatabaseFactory();
      databaseHelper = DatabaseHelper();
      await databaseHelper.database;
      
      statisticsService = StatisticsService();
    });

    group('getOverallStatistics', () {
      test('should return overall statistics with correct structure', () async {
        final result = await statisticsService.getOverallStatistics();
        
        expect(result, isA<Map<String, dynamic>>());
        expect(result['basic_stats'], isA<Map<String, dynamic>>());
        expect(result['monthly_stats'], isA<Map<String, dynamic>>());
        expect(result['process_stats'], isA<List>());
        
        // 检查基本统计
        final basicStats = result['basic_stats'] as Map<String, dynamic>;
        expect(basicStats['total_records'], isA<int>());
        expect(basicStats['total_production'], isA<double>());
        expect(basicStats['total_energy_consumption'], isA<double>());
        expect(basicStats['total_carbon_emission'], isA<double>());
        
        // 检查月度统计
        final monthlyStats = result['monthly_stats'] as Map<String, dynamic>;
        expect(monthlyStats['monthly_records'], isA<int>());
        expect(monthlyStats['monthly_production'], isA<double>());
        expect(monthlyStats['monthly_carbon_emission'], isA<double>());
        
        // 检查工艺统计
        final processStats = result['process_stats'] as List;
        expect(processStats, isA<List>());
      });

      test('should handle database with records', () async {
        final result = await statisticsService.getOverallStatistics();
        
        final basicStats = result['basic_stats'] as Map<String, dynamic>;
        expect(basicStats['total_records'], greaterThanOrEqualTo(0));
        expect(basicStats['total_production'], greaterThanOrEqualTo(0.0));
        expect(basicStats['total_energy_consumption'], greaterThanOrEqualTo(0.0));
        expect(basicStats['total_carbon_emission'], greaterThanOrEqualTo(0.0));
      });
    });

    group('getTrendAnalysis', () {
      test('should return trend analysis with correct structure', () async {
        final result = await statisticsService.getTrendAnalysis(
          timeUnit: 'month',
          limit: 12,
        );
        
        expect(result, isA<Map<String, dynamic>>());
        expect(result['time_unit'], equals('month'));
        expect(result['limit'], equals(12));
        expect(result['trend_data'], isA<List>());
      });

      test('should handle different time units', () async {
        final dayResult = await statisticsService.getTrendAnalysis(
          timeUnit: 'day',
          limit: 30,
        );
        expect(dayResult['time_unit'], equals('day'));
        
        final yearResult = await statisticsService.getTrendAnalysis(
          timeUnit: 'year',
          limit: 5,
        );
        expect(yearResult['time_unit'], equals('year'));
      });
    });

    group('getComparisonAnalysis', () {
      test('should return comparison analysis with correct structure', () async {
        final result = await statisticsService.getComparisonAnalysis(
          comparisonType: 'process',
        );
        
        expect(result, isA<Map<String, dynamic>>());
        expect(result['comparison_type'], equals('process'));
        expect(result['comparison_data'], isA<List>());
      });

      test('should handle different comparison types', () async {
        final processResult = await statisticsService.getComparisonAnalysis(
          comparisonType: 'process',
        );
        expect(processResult['comparison_type'], equals('process'));
        
        final timeResult = await statisticsService.getComparisonAnalysis(
          comparisonType: 'time',
        );
        expect(timeResult['comparison_type'], equals('time'));
      });
    });

    group('exportStatisticsReport', () {
      test('should export CSV report successfully', () async {
        final result = await statisticsService.exportStatisticsReport(reportType: 'overall');
        
        expect(result, isA<String>());
        expect(result.isNotEmpty, isTrue);
        expect(result.contains('总体统计报表'), isTrue);
      });

      test('should include all required sections in CSV', () async {
        final csvContent = await statisticsService.exportStatisticsReport(reportType: 'comprehensive');
        
        // 检查是否包含必要的部分
        expect(csvContent.contains('综合统计报表'), isTrue);
        expect(csvContent.contains('总体统计'), isTrue);
        expect(csvContent.contains('趋势分析'), isTrue);
        expect(csvContent.contains('对比分析'), isTrue);
      });
    });

    group('Error Handling', () {
      test('should handle database errors gracefully', () async {
        // 这个测试可能需要模拟数据库错误
        // 在实际环境中，数据库错误会被捕获并重新抛出
        expect(
          () => statisticsService.getOverallStatistics(),
          returnsNormally,
        );
      });
    });
  });
} 